package com.lq.javawebTest.core.utils;

import com.lq.javawebTest.core.entity.HttpResponse;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

public class HttpResponseHandler {

    // 将响应对象序列化成字符串报文
    public static String build(HttpResponse response){
        StringBuilder sb = new StringBuilder();
        sb.append(response.getProtocol()).append(" ")
                .append(response.getCode()).append(" ")
                .append(response.getMessage()).append("\r\n");

        //拼接首部信息
        for(Map.Entry<String,String> entry : response.getHeader().entrySet()){
            sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\r\n");
        }
        //响应需要两个\r\n
        sb.append("\r\n");

        if(response.getBody() != null){
            sb.append(response.getBody());
        }
        return sb.toString();
    }

    public static void writeResponse(HttpResponse response, OutputStream outputStream){
        //将响应的回复报文实例转化为String实例，再转化为流状态，输入到网页输出流中
        String message = build(response);
        try {
            outputStream.write(message.getBytes());
            outputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
